package com.ops.controller;

import com.ops.entity.Fault;
import com.ops.entity.Report;
import com.ops.service.FaultService;
import com.ops.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 故障管理控制器
 * 处理故障记录的导入和查询等操作
 */
@RestController
@RequestMapping("/api/faults")
public class FaultController {
    
    @Autowired
    private FaultService faultService;
    @Autowired
    private ReportService reportService;
    
    /**
     * 导入故障数据
     * 支持Excel文件导入故障记录
     * 
     * @param file Excel文件
     * @param reportUuid 报告UUID
     * @param hospitalId 医院ID
     * @param demandYear 需求年份
     * @return 导入结果
     */
    @PostMapping("/import")
    public ResponseEntity<?> importFaults(
        @RequestParam("file") MultipartFile file,
        @RequestParam("reportUuid") String reportUuid,
        @RequestParam("hospitalId") String hospitalId,
        @RequestParam("demandYear") String demandYear
    ) {
        try {
            int count = faultService.importExcel(file, reportUuid, hospitalId, demandYear);
            Map<String, Object> response = new HashMap<>();
            response.put("count", count);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取故障列表
     * 根据报告UUID、医院ID和年份查询故障记录
     */
    @GetMapping("/{reportUuid}/{hospitalId}/{demandYear}")
    public ResponseEntity<List<Fault>> getFaults(
        @PathVariable String reportUuid,
        @PathVariable String hospitalId,
        @PathVariable String demandYear
    ) {
        List<Fault> faults = faultService.getFaults(reportUuid, hospitalId, demandYear);
        return ResponseEntity.ok(faults);
    }

    /**
     * 获取月度故障统计数据
     * 
     * @param reportUuid 报告UUID
     * @return 月度故障统计信息
     */
    @GetMapping("/{reportUuid}/monthly-fault-stats")
    @ResponseBody
    public ResponseEntity<List<Map<String, Object>>> getMonthlyFaultStats(
            @PathVariable String reportUuid
    ) {
        Report report = reportService.getReportByUuid(reportUuid);
        List<Map<String, Object>> stats = faultService.getMonthlyFaultStats(
                reportUuid,
                report.getHospitalId(),
                report.getDemandYear()
        );
        return ResponseEntity.ok(stats);
    }
} 